package com.itcm.skymail.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcm.common.constant.WareConstant;
import com.itcm.common.utils.PageUtils;
import com.itcm.common.utils.Query;
import com.itcm.skymail.ware.dao.PurchaseDao;
import com.itcm.skymail.ware.entity.PurchaseDetailEntity;
import com.itcm.skymail.ware.entity.PurchaseEntity;
import com.itcm.skymail.ware.entity.vo.FinishVo;
import com.itcm.skymail.ware.entity.vo.MergeVo;
import com.itcm.skymail.ware.entity.vo.PurchaseTaskVo;
import com.itcm.skymail.ware.service.PurchaseDetailService;
import com.itcm.skymail.ware.service.PurchaseService;
import com.itcm.skymail.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService detailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils listUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wapper = new QueryWrapper<>();

        wapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wapper
        );

        return new PageUtils(page);
    }

    // 合并整单
    @Transactional
    @Override
    public void merge(MergeVo vo) {
        Long purchaseId = vo.getPurchaseId();
        if (purchaseId == null) {
            // 先创建一个采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        List<Long> items = vo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = items.stream().map(i -> {
            PurchaseDetailEntity detail = new PurchaseDetailEntity();
            detail.setId(i);
            detail.setPurchaseId(finalPurchaseId);
            detail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return detail;
        }).collect(Collectors.toList());
        detailService.updateBatchById(detailEntities);
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Transactional
    @Override
    public void received(List<Long> purchaseIds) {
        // 1. 根据id过滤出可领取的订单
        List<PurchaseEntity> purchaseEntityList = purchaseIds.stream().map(id -> {
            PurchaseEntity purchase = this.getById(id);
            return purchase;
        }).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            } else {
                return false;
            }
        }).map(purchase -> {
            purchase.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            purchase.setUpdateTime(new Date());
            return purchase;
        }).collect(Collectors.toList());

        // 2. 更新订单状态
        this.updateBatchById(purchaseEntityList);

        // 3. 更新需求单状态
        purchaseEntityList.forEach(item -> {
            detailService.updateToBuyingByPurchaseId(item.getId());
        });
    }

    @Transactional
    @Override
    public void finish(FinishVo vo) {
        // 1. 更新采购单状态 purchase  采购单状态 由采购单详情是否全部完成来决定 （已完成/有异常）
        // 2. 更新采购单中 采购单详情状态 purchase detail
        // 3. 入库 即完成的库存增加
        Long purchaseId = vo.getId();

        List<PurchaseTaskVo> items = vo.getItems();
        // 是否全部完成标记
        boolean flag = true;
        List<PurchaseDetailEntity> detailList = new ArrayList<>();
        for (PurchaseTaskVo item : items) {
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()) {
                flag = false;
            } else {
                // 成功完成的 做入库操作
                System.out.println("完成 。。 准备入库");
                System.out.println(item.getItemId());
                PurchaseDetailEntity detailEntity = detailService.getById(item.getItemId());
                System.out.println(detailEntity);
                System.out.println("-------");

                Long skuId = detailEntity.getSkuId();
                Long wareId = detailEntity.getWareId();
                Integer skuNum = detailEntity.getSkuNum();
                wareSkuService.addStock(skuId, wareId, skuNum);
            }
            PurchaseDetailEntity detail = new PurchaseDetailEntity();
            detail.setId(item.getItemId());
            detail.setStatus(item.getStatus());
            /*
              这里简化了需求 实际上应该 设计成需求数量 和 实际完成数据量 还有未完成原因
              这里模拟业务 只有已完成和未完成 默认未完成就是为采购
             */
            detailList.add(detail);
        }
        detailService.updateBatchById(detailList);
        // 根据标记是否全部完成 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}